<template>
	<view class="page ex-mall-tab-page" :class="[$themeClass('panel-content-bg-color')]">
		<view class="header-fill">
			<!-- #ifdef MP-WEIXIN -->
			<view class="ex-mall-header-mp-weixin-fill">【 🚚 预约总览 】</view>
			<!-- #endif -->
		</view>

		<view class="container">
			<view class="header">
				<view class="title"></view>
				<view class="btns">
					<view class="btn checked-all ex-mall-header-btn" :class="[$themeClass('header-btn-left-bg-color')]" @click="checkedAll">
						<text class="icon ex-mall-header-btn-icon" :class="[isCheckedAll?'ri-check-line':'ri-checkbox-blank-line', $themeClass('header-btn-left-icon-color')]"></text>
					</view>
					<view class="btn remove ex-mall-header-btn" :class="[$themeClass('header-btn-left-further-bg-color')]" @click="isRemoveEdit=!isRemoveEdit">
						<text class="icon ex-mall-header-btn-icon" :class="[isRemoveEdit?'ri-close-line':'ri-delete-bin-line', $themeClass('header-btn-left-icon-further-color')]"></text>
					</view>
				</view>
			</view>
			<view class="content list">
        <view class="item" v-if="Object.keys(shopCard).length === 0" style="align-items: center; justify-content: center">
          <u-empty text="暂无预约信息" mode="list"></u-empty>
        </view>
				<view v-else class="item" v-for="(id, xi) in Object.keys(shopCard)" :key="xi">
					<view class="left">
						<view class="checkbox">
							<view class="icon" @click="toggleChecked(shopCard[id])" :class="[shopCard[id].checked?'ri-checkbox-fill '+$themeClass('checkbox-color'):'ri-checkbox-blank-line']"></view>
						</view>
						<view class="thumbnail">
							<image class="img" mode="aspectFill" :src="shopCard[id].info.pictureUrl.split(',')[0]"></image>
						</view>
						<view class="info">
							<view class="title">{{shopCard[id].info.goodsName}}<text class="spec"></text></view>
              <view class="title">
                <view class="spec" :key="i" v-for="(styleKey, i) in Object.keys(JSON.parse(shopCard[id].info.value))">
                  <span v-if="i === 0">{{JSON.parse(shopCard[id].info.value)[styleKey]}}</span>
                  <span v-else><span v-html="'&nbsp;-&nbsp;'"></span>{{JSON.parse(shopCard[id].info.value)[styleKey]}}</span>
                </view>
              </view>
							<view class="price">￥{{shopCard[id].info.price}}</view>
						</view>
					</view>
					<view class="right">
						<view class="numberbox">
							<view class="icon plus ri-add-line" @click="quantityPlus(id)" :class="[$themeClass('checkbox-color')]"></view>
							<!-- #ifdef MP-WEIXIN -->
							<input class="input" style="margin-left: 0 !important;" type="number" disabled :data-index="xi" :value="shopCard[id].count" />
							<!-- #endif -->
							<!-- #ifndef MP-WEIXIN -->
							<!-- #endif -->
							<view class="icon minus ri-subtract-line" @click="quantityMinus(id)"></view>
						</view>
					</view>
				</view>
			</view>

      <view class="contact-content" :class="[$themeClass('goods-content-bg-color')]">
        <view class="orderForm">
          <view class="receiver">
            <view class="title" :class="[$themeClass('goods-title-color')]">预约信息</view>
            <view class="item">
              <u-input class="input" v-model="orderForm.name" placeholder="称呼"></u-input>
            </view>
            <view class="item">
              <u-input class="input" v-model="orderForm.phone" placeholder="备注（必填）" type="number"></u-input>
            </view>
            <view class="item">
              <u-input class="input" @click="datePickerShow = true" v-model="defaultTime"></u-input>
            </view>
            <view class="item">
              <u-input class="input" v-model="timeRangeValue" @click="timePickerShow = true"></u-input>
            </view>
            <view class="item">
              <u-input class="input" v-model="orderForm.remark" placeholder="其他问题（选填）"></u-input>
            </view>
          </view>
        </view>
      </view>
		</view>
		<view class="footer">
			<view class="submit" v-if="!isRemoveEdit">
				<view class="btn" @click="submitOrder" :class="[$themeClass('search-btn-bg-color'), $themeClass('search-btn-color')]">
					<view class="label">提交预约</view>
					<view class="amount">￥{{totalAmount.toFixed(2)}}</view>
				</view>
			</view>
			<view class="remove" v-else>
				<view class="btn" :class="[$themeClass('search-btn-bg-color'), $themeClass('search-btn-color')]" @click="removeItem">删除选中</view>
			</view>
		</view>
    <u-modal :confirm-text="'确认'" :show-cancel-button="true" @cancel="this.orderConfirm = false" @confirm="confirmOrder" v-model="orderConfirm" :content="'確定预约后, 预约信息可在个人中心查看并通过预约号取货, 确认预约?'"></u-modal>
    <u-picker mode="selector" :default-selector="[0]" v-model="timePickerShow" :range="timeRange" range-key="key" @confirm="confirmTime"></u-picker>
    <u-picker mode="time" v-model="datePickerShow" :params="dateParams" end-year="2030" @confirm="confirmDate"></u-picker>
  </view>
</template>

<script>
import util from "../../common/js/util";
import UModal from "../../libs/uview-ui/components/u-modal/u-modal";
import UPicker from "../../libs/uview-ui/components/u-picker/u-picker";
import UEmpty from "../../libs/uview-ui/components/u-empty/u-empty";
import {submit} from "../../api/order";

export default {
    components: { UModal, UPicker, UEmpty },
		data() {
			return {
				isCheckedAll: false,
				isRemoveEdit: false,
				totalAmount: 0,
				carts: [],
        shopCard: {},
        orderForm: {
        },
        orderConfirm: false,
        timePickerShow: false,
        datePickerShow: false,
        defaultTime: "",
        timeRangeValue: '08:00-09:00',
        dateParams: {
          year: true,
          month: true,
          day: true,
        },
        timeRange: [
          {
            title: '08:00-09:00',
            key: '08:00-09:00'
          },
          {
            title: '15:30-16:30',
            key: '15:30-16:30'
          }
        ]
			}
		},
		mounted() {
			this.load()
			this.$emit('loaded', {
				name: 'shoppingcart'
			})
		},
		methods: {
      initTime() {
        var date = new Date(),
            year = date.getFullYear(),
            month = date.getMonth() + 1,
            day = date.getDate() + 1
        month >= 1 && month <= 9 ? (month = "0" + month) : "";
        day >= 0 && day <= 9 ? (day = "0" + day) : "";
        this.defaultTime = year + '-' + month + '-' + day
      },
      confirmTime(e) {
        this.timeRangeValue = this.timeRange[e[0]].title
      },
      confirmDate(e) {
        this.defaultTime = e.year + '-' + e.month + '-' + e.day
      },
      confirmOrder() {
        const associatedGoods = {}
        Object.keys(this.shopCard).forEach((id) => {
          if (this.shopCard[id].checked) {
            associatedGoods[id] = this.shopCard[id]
          }
        })

        this.shipAddress = ''
        submit( {
          associatedGoods: JSON.stringify(associatedGoods),
          shippingAddress: this.shipAddress,
          shipType: this.orderForm.shipType,
          receiverName: this.orderForm.name,
          receiverPhone: this.orderForm.phone,
          receiverEmail: this.orderForm.email,
          time: this.defaultTime,
          timeRange: this.timeRangeValue,
          remark: this.orderForm.remark
        }).then((res) => {
          const order = res.data
          if (Object.keys(order).length === 0) {
            uni.showToast({
              icon: 'none',
              title: '预约创建失败!'
            })
            return
          }
          uni.showToast({
            icon: 'none',
            title: '预约创建成功!'
          })
          setTimeout(() => {
            Object.keys(this.shopCard).forEach((id) => {
              if (this.shopCard[id].checked) {
                this.$set(this.shopCard, id, null)
                delete this.shopCard[id]
              }
            })
            util.setStorage('shopCard', this.shopCard)
            this.totalAmount = 0
            uni.navigateTo({
              url: `/pages/order/result?id=${order.id}`
            });
          }, 500)
        }).catch(e => {
          console.log(e)
          uni.showToast({
            icon: 'none',
            title: e
          })
        })
      },
      submitOrder() {
        let checkCount = 0
        Object.keys(this.shopCard).forEach((id) => {
          if (this.shopCard[id].checked) {
            checkCount++
          }
        })
        if (checkCount === 0) {
          uni.showToast({
            icon: 'none',
            title: '请选择要提交的预约信息!'
          })
          return
        }

        if (this.validateOrderForm()) {
          this.orderConfirm = true
        }

        console.log(this.orderConfirm)
      },
      validateOrderForm() {
        const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (!this.orderForm.name || this.orderForm.name === '') {
          uni.showToast({
            icon: 'none',
            title: '请填写称呼!'
          })
          return false
        } else if (!this.orderForm.phone || this.orderForm.phone === '') {
          uni.showToast({
            icon: 'none',
            title: '请填写备注!'
          })
          return false
        } else {
          return true
        }
      },
      removeItem() {
        Object.keys(this.shopCard).forEach((id) => {
          if (this.shopCard[id].checked) {
            this.$set(this.shopCard, id, null)
            delete this.shopCard[id]
            util.setStorage('shopCard', this.shopCard)
          }
        })
        this.isRemoveEdit = false
      },
			load() {
        this.initTime()

        const shopCard = util.getStorage('shopCard')
        this.shopCard = !shopCard ? {} : shopCard
        Object.keys(this.shopCard).forEach((id) => {
          this.$set(this.shopCard[id], 'checked', true)
        })
        this.isCheckedAll = true
        this.calcTotal()

        const userInfo = uni.getStorageSync('userInfo')
        if (Object.keys(userInfo).length === 0 || userInfo === '') {
          return
        }
        this.orderForm.name = userInfo.name
        this.orderForm.phone = userInfo.phone
			},
			show() {
				console.log('shoppingcart on show')
        this.load()
			},
			checkedAll() {
				if (this.isCheckedAll) {
					this.isCheckedAll = false
          Object.keys(this.shopCard).forEach((id) => {
            this.$set(this.shopCard[id], 'checked', false)
          })
				} else {
					this.isCheckedAll = true
          Object.keys(this.shopCard).forEach((id) => {
            this.$set(this.shopCard[id], 'checked', true)
          })
				}
        util.setStorage('shopCard', this.shopCard)
				this.calcTotal()
			},
			toggleChecked(cartItem) {
				var checked = !cartItem.checked
				this.$set(cartItem, 'checked', checked)
				if (checked) {
          let checkCount = 0
          Object.keys(this.shopCard).forEach((id) => {
            if (this.shopCard[id].checked) {
              checkCount++
            }
          })
					if (checkCount === Object.keys(this.shopCard).length) {
						this.isCheckedAll = true
					}
				} else {
					this.isCheckedAll = false
				}
        util.setStorage('shopCard', this.shopCard)
				this.calcTotal()
			},
			quantityPlus(id) {
        const count = this.shopCard[id].count + 1
        this.$set(this.shopCard[id], 'count', count)
        util.setStorage('shopCard', this.shopCard)
				this.calcTotal()
			},
			quantityMinus(id) {
        let count = this.shopCard[id].count
				if (count > 1) {
          count--
          this.$set(this.shopCard[id], 'count', count)
				}
        util.setStorage('shopCard', this.shopCard)
				this.calcTotal()
			},
			calcTotal() {
				let totalAmount = 0
        Object.keys(this.shopCard).forEach((id) => {
          if (this.shopCard[id].checked) {
            totalAmount += this.shopCard[id].info.price * this.shopCard[id].count
          }
        })
				this.totalAmount = totalAmount
			}
		}
	}
</script>

<style lang="scss">
   input {
     margin-left: 10px !important;
   }
	.page {
		&>.header-fill {
			padding: 0 28px;
			padding-top: calc(16px + var(--status-bar-height));
			background-color: #FFFFFF;

			&>.ex-mall-header-mp-weixin-fill {
				color: #3D3D3D;
			}
		}

		&>.container {
			/* #ifndef MP-WEIXIN */
			height: calc(100vh);
			/* #endif */
			/* #ifdef MP-WEIXIN */
			height: calc(100vh);
			/* #endif */
			background-color: #FFFFFF;
			border-radius: 0 0 2em 2em;
			overflow-y: scroll;

			&>.header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12px 28px 28px 28px;
				background-color: #FFFFFF;

				&>.title {
					font-size: 28px;
					font-weight: 600;
				}

				&>.btns {
					display: flex;

					&>.btn {
						margin-left: 16px;
					}
				}
			}

			&>.content.list {
				padding-top: 10px;

				&>.item {
					display: flex;
					justify-content: space-between;
					padding: 0 28px 28px 28px;

					&:nth-child(4n-3) {
						&>.left {
							&>.thumbnail {
								&>.img {
									background-color: #0EAA90;
								}
							}
						}
					}

					&:nth-child(4n-2) {
						&>.left {
							&>.thumbnail {
								&>.img {
									background-color: #F8E3DC;
								}
							}
						}
					}

					&:nth-child(4n-1) {
						&>.left {
							&>.thumbnail {
								&>.img {
									background-color: #A8A8A9;
								}
							}
						}
					}

					&:nth-child(4n) {
						&>.left {
							&>.thumbnail {
								&>.img {
									background-color: #7F8688;
								}
							}
						}
					}

					&>.left {
						display: flex;
						align-items: center;
						flex: 1;

						&>.checkbox {
							&>.icon {
								font-size: 20px;
								color: #9093A2;
							}
						}

						&>.thumbnail {
							margin-left: 12px;

							&>.img {
								display: block;
								width: 88px;
								height: 88px;
								border-radius: 12px;
							}
						}

						&>.info {
							margin: 0 18px;
							line-height: 1;

							&>.title {
								line-height: 1.3;
								font-size: 15px;
								font-weight: 600;

								&>.spec {
                  margin-top: 10px;
                  font-size: 14px;
									color: #808080;
								}
							}

							&>.price {
								margin-top: 10px;
								font-size: 13px;
							}
						}
					}

					&>.right {
						height: 88px;
						background-color: #F7F7F7;
						border-radius: 12px;
						overflow: hidden;

						&>.numberbox {
							display: flex;
							flex-direction: column;

							&>.icon {
								display: flex;
								justify-content: center;
								align-items: center;
								width: 48px;
								height: 35px;
								font-size: 18px;
								font-weight: bold;

								&.plus {
									color: #61DAD5;
								}

								&.minus {
									color: #9093A2;
								}
							}

							&>.input {
								display: flex;
								justify-content: center;
								align-items: center;
								width: 48px;
								height: 18px;
								padding: 0 4px;
								text-align: center;
								font-size: 13px;
								color: #666666;
								box-sizing: border-box;
							}
						}
					}
				}
			}

      &>.contact-content {
        position: relative;
        z-index: 1;
        //margin-top: -5px;
        padding: 0 28px calc(54px + 18px + 18px + (env(safe-area-inset-bottom) / 2)) 28px;
        //border-radius: 10px 10px 0 0;

        & > .orderForm {
          & > .contact {
            & > .title {
              margin-top: 15px;
              font-size: 14px;
              font-weight: 600;
            }

            & > .item {
              margin-top: 15px;
              border-radius: 5px;
              border: 1px solid lightgrey;

              & > input {
                margin-left: 10px;
              }
            }
          }

          & > .transport {
            & > .title {
              margin-top: 15px;
              font-size: 14px;
              font-weight: 600;
            }

            & > .item {
              margin-top: 15px;

              & > .radio {
              }
            }
          }

          & > .receiver {
            & > .title {
              margin-top: 15px;
              font-size: 14px;
              font-weight: 600;
            }

            & > .item {
              margin-top: 15px;
              border-radius: 5px;
              border: 1px solid lightgrey;

              & > input {
                margin-left: 10px;
              }
            }
          }

          & > .address {
            & > .title {
              margin-top: 15px;
              font-size: 14px;
              font-weight: 600;
            }

            & > .item {
              margin-top: 15px;
              border-radius: 5px;
              border: 1px solid lightgrey;
              display: flex;

              & > input {
                margin-left: 10px;
              }

              & > .label {
                margin: 10px 0 10px 10px;
                font-size: 13px;
                color: lightgrey;
                width: 50px;
              }

              & > .context {
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 0 10px;
                font-size: 13px;
              }
            }
          }

          & > .shopAddress {
            & > .title {
              margin-top: 15px;
              font-size: 14px;
              font-weight: 600;
            }

            & > .item {
              margin-top: 15px;
              border-radius: 5px;
              border: 1px solid lightgrey;
              display: flex;

              & > .button711 {
                color: white;
                font-weight: 600;
                background-color: #F76842;
              }

              & > .input {
              }

              & > .label {
                margin: 10px 0 10px 10px;
                font-size: 13px;
                width: 50px;
                color: lightgrey;
              }

              & > .context {
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 0 10px;
                font-size: 13px;
              }
            }
          }

          & > .aboutUs {


            & > .collapse {
              display: flex;
              justify-content: center;
              align-items: center;
              margin-top: 20px;
              font-size: 13px;
            }
          }
        }
      }
		}

		&>.footer {
      position: fixed;
      right: 0;
      bottom: 8%;
      left: 0;
      z-index: 2;
      padding: 18px 28px calc(18px + (env(safe-area-inset-bottom) / 2)) 28px;
      background-color: #FFFFFF;
      border-radius: 34px 34px 0 0;
      overflow: hidden;

			.btn {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				height: 58px;
				padding: 0 28px;
				border-radius: 12px;
				box-sizing: border-box;
			}

			&>.submit {
				&>.label {
					font-size: 15px;
					font-weight: 600;
				}

				&>.amount {
					font-size: 14px;
				}
			}

			&>.remove {
				&>.btn {
					justify-content: center;
				}
			}
		}
	}
</style>
